package com.atguigu.test5;

/**
 * @author 路飞
 * @date 2024/3/28 15:20
 * @description 11.	请使用二分查找算法查找字符数组{"a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”}中”g”元素的位置？
 */
public class Exer11 {
    public static void main(String[] args) {
        String[] s = {"a", "b", "c", "d", "e", "f", "g", "h"};
        System.out.println(binarySearch(s, "a"));
    }

    public static int binarySearch(String[] arr, String target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (target.compareTo(arr[mid]) > 0) {
                left = mid + 1;
            } else if (target.compareTo(arr[mid]) == 0) {
                return mid;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
